package bookstore;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

/**
 * Bookインスタンスを取り扱うクラスです
 */
public class BookManager {

    public void init(ServletContext context) throws SQLException {
        context.setAttribute(Globals.CONTEXT_BOOKS, Book.loadAllData());
    }

    @SuppressWarnings("unchecked")
	public Map<String,Book> getBookMaster(ServletContext context) {
        return (Map<String, Book>) context.getAttribute(Globals.CONTEXT_BOOKS);
    }

    // 書籍マスタデータを対象に、キーワード検索を行う
    public void searchByKeyword(ServletContext context, HttpSession session,
                                String keyword) {
        Collection<Book> collection = getBookMaster(context).values();

        // マッチしたBookインスタンスをsessionスコープに登録
        Book[] books = (Book[]) collection.toArray(new Book[collection.size()]);
        session.setAttribute(Globals.SESSION_SEARCHED_BOOKS,
                             Book.searchByKeyword(books, keyword));
    }

    // 指定した書籍番号を持つBook配列を取得
    public Book[] getSelectedBooks(HttpSession session, String[] ids) {
        Book[] searchedBooks = (Book[]) session.getAttribute(Globals.SESSION_SEARCHED_BOOKS);
        return Book.searchByIds(searchedBooks, ids);
    }

}